"""
用户管理路由 - CRUD操作
"""
from flask import request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from app.blueprints.api import api_bp
from app.models.user import User, StudentProfile, TeacherProfile
from app.models.log import SystemLog
from app.extensions import db
from datetime import datetime


@api_bp.route('/users', methods=['POST'])
@jwt_required()
def create_user():
    """创建用户"""
    try:
        current_user_id = int(get_jwt_identity())
        current_user = User.query.get(current_user_id)
        
        if current_user.role != 'admin':
            return jsonify({
                'success': False,
                'error': 'Permission denied'
            }), 403
        
        data = request.get_json()
        
        # 验证必填字段
        required_fields = ['username', 'password', 'role', 'first_name', 'last_name', 'college', 'department']
        for field in required_fields:
            if field not in data or not data[field]:
                return jsonify({
                    'success': False,
                    'error': f'Missing required field: {field}'
                }), 400
        
        # 检查用户名是否已存在
        if User.query.filter_by(username=data['username']).first():
            return jsonify({
                'success': False,
                'error': 'Username already exists'
            }), 400
        
        # 检查邮箱是否已存在（如果提供了邮箱）
        email = data.get('email')
        if email and User.query.filter_by(email=email).first():
            return jsonify({
                'success': False,
                'error': 'Email already exists'
            }), 400
        
        # 创建用户
        user = User(
            username=data['username'],
            email=email if email else None,
            role=data['role'],
            first_name=data['first_name'],
            last_name=data['last_name'],
            college=data['college'],
            department=data['department'],
            phone=data.get('phone', '')
        )
        user.set_password(data['password'])
        
        db.session.add(user)
        db.session.flush()
        
        # 根据角色创建对应的profile
        if data['role'] == 'student':
            profile = StudentProfile(
                user_id=user.id,
                student_id=data.get('student_id', ''),
                major=data.get('major', ''),
                grade_level=data.get('grade_level'),
                enrollment_date=datetime.strptime(data['enrollment_date'], '%Y-%m-%d').date() if 'enrollment_date' in data else None
            )
            db.session.add(profile)
        elif data['role'] == 'teacher':
            profile = TeacherProfile(
                user_id=user.id,
                employee_id=data.get('employee_id', ''),
                department=data.get('department', ''),
                title=data.get('title', ''),
                bio=data.get('bio', '')
            )
            db.session.add(profile)
        
        # 记录日志
        log = SystemLog(
            user_id=current_user_id,
            action='create',
            resource_type='user',
            resource_id=str(user.id),
            ip_address=request.remote_addr,
            status='success',
            level='INFO',
            message=f'Created user {user.username}'
        )
        db.session.add(log)
        
        db.session.commit()
        
        return jsonify({
            'success': True,
            'message': 'User created successfully',
            'data': user.to_dict()
        }), 201
        
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@api_bp.route('/users/<int:user_id>', methods=['PUT'])
@jwt_required()
def update_user(user_id):
    """更新用户信息"""
    try:
        current_user_id = int(get_jwt_identity())
        current_user = User.query.get(current_user_id)
        
        # 只有管理员或用户本人可以更新
        if current_user.role != 'admin' and current_user_id != user_id:
            return jsonify({
                'success': False,
                'error': 'Permission denied'
            }), 403
        
        user = User.query.get(user_id)
        if not user:
            return jsonify({
                'success': False,
                'error': 'User not found'
            }), 404
        
        data = request.get_json()
        
        # 更新基本信息
        if 'email' in data:
            email = data['email']
            if email and email != user.email:
                if User.query.filter_by(email=email).first():
                    return jsonify({
                        'success': False,
                        'error': 'Email already exists'
                    }), 400
                user.email = email
            elif not email:
                user.email = None
        
        if 'first_name' in data:
            user.first_name = data['first_name']
        if 'last_name' in data:
            user.last_name = data['last_name']
        if 'college' in data:
            user.college = data['college']
        if 'department' in data:
            user.department = data['department']
        if 'phone' in data:
            user.phone = data['phone']
        if 'is_active' in data and current_user.role == 'admin':
            user.is_active = data['is_active']
        
        # 更新密码
        if 'password' in data:
            user.set_password(data['password'])
        
        # 更新profile
        if user.role == 'student' and user.student_profile:
            if 'major' in data:
                user.student_profile.major = data['major']
            if 'grade_level' in data:
                user.student_profile.grade_level = data['grade_level']
            if 'enrollment_date' in data and data['enrollment_date']:
                try:
                    user.student_profile.enrollment_date = datetime.strptime(data['enrollment_date'], '%Y-%m-%d').date()
                except Exception:
                    pass
        elif user.role == 'teacher' and user.teacher_profile:
            if 'department' in data:
                user.teacher_profile.department = data['department']
            if 'title' in data:
                user.teacher_profile.title = data['title']
            if 'bio' in data:
                user.teacher_profile.bio = data['bio']
        
        user.updated_at = datetime.utcnow()
        
        # 记录日志
        log = SystemLog(
            user_id=current_user_id,
            action='update',
            resource_type='user',
            resource_id=str(user_id),
            ip_address=request.remote_addr,
            status='success',
            level='INFO',
            message=f'Updated user {user.username}'
        )
        db.session.add(log)
        
        db.session.commit()
        
        return jsonify({
            'success': True,
            'message': 'User updated successfully',
            'data': user.to_dict()
        }), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@api_bp.route('/users/<int:user_id>', methods=['DELETE'])
@jwt_required()
def delete_user(user_id):
    """删除用户"""
    try:
        current_user_id = int(get_jwt_identity())
        current_user = User.query.get(current_user_id)
        
        if current_user.role != 'admin':
            return jsonify({
                'success': False,
                'error': 'Permission denied'
            }), 403
        
        # 不能删除自己
        if current_user_id == user_id:
            return jsonify({
                'success': False,
                'error': 'Cannot delete yourself'
            }), 400
        
        user = User.query.get(user_id)
        if not user:
            return jsonify({
                'success': False,
                'error': 'User not found'
            }), 404
        
        username = user.username
        
        # 记录日志
        log = SystemLog(
            user_id=current_user_id,
            action='delete',
            resource_type='user',
            resource_id=str(user_id),
            ip_address=request.remote_addr,
            status='success',
            level='WARNING',
            message=f'Deleted user {username}'
        )
        db.session.add(log)
        
        # 删除用户（级联删除相关数据）
        db.session.delete(user)
        db.session.commit()
        
        return jsonify({
            'success': True,
            'message': 'User deleted successfully'
        }), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@api_bp.route('/users/batch', methods=['POST'])
@jwt_required()
def batch_create_users():
    """批量创建用户"""
    try:
        current_user_id = int(get_jwt_identity())
        current_user = User.query.get(current_user_id)
        
        if current_user.role != 'admin':
            return jsonify({
                'success': False,
                'error': 'Permission denied'
            }), 403
        
        data = request.get_json()
        users_data = data.get('users', [])
        
        if not users_data:
            return jsonify({
                'success': False,
                'error': 'No users data provided'
            }), 400
        
        success_count = 0
        fail_count = 0
        errors = []
        
        for idx, user_data in enumerate(users_data):
            try:
                # 检查必填字段
                required = ['username', 'password', 'role', 'first_name', 'last_name', 'college', 'department']
                if not all(k in user_data and user_data[k] for k in required):
                    errors.append(f"Row {idx+1}: Missing required fields")
                    fail_count += 1
                    continue
                
                # 检查重复
                if User.query.filter_by(username=user_data['username']).first():
                    errors.append(f"Row {idx+1}: Username '{user_data['username']}' already exists")
                    fail_count += 1
                    continue
                
                # 创建用户
                user = User(
                    username=user_data['username'],
                    email=user_data.get('email') if user_data.get('email') else None,
                    role=user_data['role'],
                    first_name=user_data['first_name'],
                    last_name=user_data['last_name'],
                    college=user_data['college'],
                    department=user_data['department']
                )
                user.set_password(user_data['password'])
                db.session.add(user)
                db.session.flush()
                
                # 创建profile
                if user_data['role'] == 'student':
                    profile = StudentProfile(
                        user_id=user.id,
                        student_id=user_data.get('student_id', ''),
                        major=user_data.get('major', '')
                    )
                    db.session.add(profile)
                
                success_count += 1
                
            except Exception as e:
                errors.append(f"Row {idx+1}: {str(e)}")
                fail_count += 1
                continue
        
        db.session.commit()
        
        return jsonify({
            'success': True,
            'data': {
                'success_count': success_count,
                'fail_count': fail_count,
                'errors': errors
            }
        }), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@api_bp.route('/users/statistics', methods=['GET'])
@jwt_required()
def get_user_statistics():
    """获取用户统计信息"""
    try:
        current_user_id = int(get_jwt_identity())
        current_user = User.query.get(current_user_id)
        
        if current_user.role != 'admin':
            return jsonify({
                'success': False,
                'error': 'Permission denied'
            }), 403
        
        total_users = User.query.count()
        admin_count = User.query.filter_by(role='admin').count()
        teacher_count = User.query.filter_by(role='teacher').count()
        student_count = User.query.filter_by(role='student').count()
        active_users = User.query.filter_by(is_active=True).count()
        inactive_users = User.query.filter_by(is_active=False).count()
        
        return jsonify({
            'success': True,
            'data': {
                'total_users': total_users,
                'admin_count': admin_count,
                'teacher_count': teacher_count,
                'student_count': student_count,
                'active_users': active_users,
                'inactive_users': inactive_users
            }
        }), 200
        
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500








